﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xunit.Abstractions;
using Xunit;

namespace _001.日刷
{
    public class _50_Pow
    {
        /// <summary>
        /// https://leetcode.cn/problems/powx-n/
        /// </summary>
        public class Solution
        {
            /// <summary>
            /// 
            /// </summary>
            /// <param name="x"></param>
            /// <param name="n"></param>
            /// <returns></returns>
            public double MyPow3(double x, int n)
            {
                double N = n;
                if (n < 0)
                {
                    x = 1 / x;
                    N = -N;
                }

                double ans = 1;
                for (int i = 0; i < N; i++)
                {
                    ans *= x;
                }

                return ans;
            }

            public double Power2(double x, int n)
            {
                return Math.Pow(x, n);
            }

            /// <summary>
            /// 2021-8-24 注意 -2147483648  为n时，，-n会溢出，所以应该先转 Long，再转 负数
            /// 执行用时：36 ms, 在所有 C# 提交中击败了96.15%的用户
            /// 内存消耗：15.3 MB, 在所有 C# 提交中击败了70.00%的用户
            /// </summary>
            /// <param name="x"></param>
            /// <param name="n"></param>
            /// <returns></returns>
            public double MyPow(double x, int n)
            {
                if (n == 0 || x == 1) return 1;
                return n < 0 ? 1.0 / quickMul(x, -(long)n) : quickMul(x, n);
            }

            public double quickMul(double x, long n)
            {
                if (n == 1) return x;
                double r = quickMul(x, n / 2);
                if (n % 2 != 0) return r * r * x;
                else return r * r;
            }
        }


        ITestOutputHelper output;
        public _50_Pow(ITestOutputHelper output)
        {
            this.output = output;
        }

        [Fact]
        public void Test1()
        {
            Solution S = new Solution();

            //output.WriteLine("" + S.MyPow(2.0,  -2147483647));
            //output.WriteLine("" + S.Power2(2.0, -2147483648));
            //output.WriteLine("" + S.Power3(2.00000, 10));
            output.WriteLine("" + S.MyPow(2.0, -2147483648));

        }
    }
}
